package concurrency.ping_pong.semaphore;

import java.util.concurrent.Semaphore;

public class PingPong {
	
	private int repetition;
	
	// === VARIABLES PARTAGEES ===
	private Semaphore semPing;
	private Semaphore semPong;
	// ===========================
	
	public PingPong(int repetition) {
		this.repetition = repetition;
		// === INITIALISATION ===
		semPing = new Semaphore(1);
		semPong = new Semaphore(0);
		// ======================
	}
	
	private class Ping extends Thread {
		
		@Override
		public void run() {
			for (int i = 0; i < repetition; i++) {
				try {
					semPing.acquire(); // P(semPing)
					// Debut SC
					System.out.print("Ping-");
					// Fin SC
					semPong.release(); // V(semPong)
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private class Pong extends Thread {
		
		@Override
		public void run() {
			for (int i = 0; i < repetition; i++) {
				try {
					semPong.acquire(); // P(semPong)
					// Debut SC
					System.out.println("Pong");
					// Fin SC
					semPing.release(); // V(semPing)
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		PingPong ping_pong = new PingPong(2000);
		Ping ping = ping_pong.new Ping();
		Pong pong = ping_pong.new Pong();
		ping.start();
		pong.start();
	}
}
